Skip to content

Sistema de Login y Registro con Autenticación JWT#6

Open
JMLTUnderCode wants to merge 23 commits intomainfrom
login-register-system
Open

Sistema de Login y Registro con Autenticación JWT#6
JMLTUnderCode wants to merge 23 commits intomainfrom
login-register-system

Conversation

@JMLTUnderCode
Copy link
Owner

Pull Request: Sistema de Login y Registro con Autenticación JWT

Resumen

Este PR implementa el sistema completo de login y registro de usuarios en el frontend de Clontube, integrando la autenticación JWT con el backend Django REST desplegado en Render. Se siguen buenas prácticas de ReactJS, separación de responsabilidades y seguridad en el manejo de tokens y rutas protegidas.


Cambios principales

1. Arquitectura de Autenticación

  • Se creó un AuthenticationProvider con contexto, reducer y custom hook para manejar el estado de autenticación global.
  • El estado de autenticación se sincroniza automáticamente con localStorage para persistencia de sesión.
  • El login realiza un fetch seguro a la API (/api/login/), recibe y almacena el token JWT.
  • El logout limpia el estado y el almacenamiento local.

2. Gestión de rutas y navegación

  • Se integró react-router-dom para navegación eficiente entre páginas.
  • Se configuró el BrowserRouter con basename="/Clontube" para soportar despliegues en subdirectorios.
  • Se implementó la navegación programática tras login y logout usando useNavigate.
  • Se añadieron rutas protegidas para que solo usuarios autenticados accedan a MainPage.

3. Componentes y flujo de UI

  • StartPage contiene el sistema de login y registro.
  • FormLogin maneja el envío de credenciales, muestra errores y redirige tras login exitoso.
  • FormRegister permite crear usuarios (sin iniciar sesión automáticamente).
  • MainPage muestra la sesión activa y permite cerrar sesión.
  • Se mejoró la experiencia visual y validación de formularios.

4. CORS y seguridad

  • Se documentó y aplicó la configuración de CORS en el backend Django para permitir peticiones seguras desde el frontend local y desplegado.
  • Se recomienda no usar CORS_ALLOW_ALL_ORIGINS en producción y solo permitir orígenes necesarios.

5. Testing y buenas prácticas

  • Se añadieron tests unitarios para los principales componentes y lógica de autenticación.
  • Se configuró Vitest y React Testing Library para pruebas automáticas.
  • Se agregó un workflow de GitHub Actions para ejecutar los tests en cada PR y push.

Archivos principales modificados/creados

  • src/providers/AuthenticationProvider.tsx
  • src/hooks/useAuthentication.ts
  • src/reducers/authReducer.ts
  • src/pages/StartPage.tsx
  • src/pages/MainPage.tsx
  • src/components/FormLogin.tsx
  • src/components/FormRegister.tsx
  • src/App.tsx
  • vite.config.ts
  • backend/settings.py (documentación y ejemplo de CORS)

…n handler y se agrega a la funcionalidad del boton.
…este logeado. Siempre redireccionara a la startpage.
…del usuario que ha logeado y un boton de logout. El logout aprovecha la funcion provista por el context authentication
…ica de guardado en localstorage. Actualizacion de tipos.
…usion de tipos y acciones para Authentication context, provider, state
…ege la ruta main en caso de no haber login activo. Se incluye la pagina principal
… Se cuenta con 3 acciones clave, login que guardan el token JWT de acceso y refresco junto a la informacion del usuario. Logout resetea el estado. Login failed actualiza los intentos fallidos de login.
…de login view y se redireciona a la vista de login. Falta manejar errores de registro y en caso de error de peticion
@JMLTUnderCode JMLTUnderCode self-assigned this Sep 27, 2025
@JMLTUnderCode JMLTUnderCode added enhancement New feature or request Improvement Improvement of code, functionality, and logic. labels Sep 27, 2025
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR implements a complete authentication system with JWT tokens for the Clontube frontend, integrating login and registration functionality with a deployed Django REST backend. The implementation follows React best practices with context providers, reducers, and protected routes.

Key changes include:

  • Authentication state management with JWT token persistence
  • Protected routing system with automatic redirects
  • Login/registration forms with API integration

Reviewed Changes

Copilot reviewed 17 out of 20 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
vite.config.ts Added commented proxy configuration for API routing
src/utils/types.ts Added authentication types and renamed existing types for consistency
src/reducers/loginViewReducer.ts Updated type references and removed unused code
src/reducers/authenticationReducer.ts New reducer for authentication state management
src/providers/LoginViewProvider.tsx Updated imports and added localStorage sync function
src/providers/AuthenticationProvider.tsx New provider for authentication context
src/pages/MainPage.tsx New main page with logout functionality
src/main.tsx Wrapped app with AuthenticationProvider
src/hooks/useLoginView.ts Fixed import path casing
src/hooks/useAuthentication.ts New hook for authentication context
src/contexts/AuthenticationContext.tsx New authentication context
src/components/ProtectedRoute.tsx New component for route protection
src/components/FormLogin.tsx Added login functionality and navigation
src/App.tsx Added routing configuration with protected routes
package.json Added react-router-dom dependency
backend/settings.py Added CORS configuration for frontend integration

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

Copilot reviewed 20 out of 23 changed files in this pull request and generated 4 comments.


Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Comment on lines +41 to +45
/*React.useEffect(() => {
updateLocalStorageLoginView(state);
}, [state]);
*/

Copy link

Copilot AI Sep 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This commented out useEffect should either be implemented or removed entirely. Commented code blocks create confusion about intended functionality.

Suggested change
/*React.useEffect(() => {
updateLocalStorageLoginView(state);
}, [state]);
*/
React.useEffect(() => {
updateLocalStorageLoginView(state);
}, [state]);

Copilot uses AI. Check for mistakes.
Comment on lines +24 to +33
/*
server: {
proxy: {
'/api': {
target: 'https://backend-9tcm.onrender.com',
changeOrigin: true,
secure: false,
},
}
} */ No newline at end of file
Copy link

Copilot AI Sep 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This commented proxy configuration should be removed if not needed, or properly integrated into the config object if it serves a purpose for development.

Copilot uses AI. Check for mistakes.
Comment on lines +41 to +44
// Manejar error de registro
}
} catch {
// Manejar error de peticion
Copy link

Copilot AI Sep 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Empty catch and error handling blocks provide no feedback to users. These should implement proper error handling with user-facing messages or logging.

Copilot uses AI. Check for mistakes.
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request Improvement Improvement of code, functionality, and logic.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant